package com.warrior.superdata.service.impl;

import com.warrior.superdata.constants.ResultCode;
import com.warrior.superdata.dds.DataSourceHelp;
import com.warrior.superdata.enums.DatasourceType;
import com.warrior.superdata.enums.OperateType;
import com.warrior.superdata.handler.SqlHandler;
import com.warrior.superdata.mysql.entity.dto.ApiDatasourceDto;
import com.warrior.superdata.service.InsertSqlService;
import com.warrior.superdata.exceptionhandler.ApplicationException;
import com.warrior.superdata.mysql.entity.dto.ApiInfoDetailDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.Statement;

/**
 * @Description:
 * @ClassName: MysqlInsertSqlServiceImpl.java
 * @date: 2022/3/10 18:13
 * @author xujian
 */
@Service
@Slf4j
public class MysqlInsertSqlServiceImpl implements InsertSqlService {

    @Autowired
    private DataSourceHelp dataSourceHelp;

    @Autowired
    private SqlHandler sqlHandler;

    @Override
    public String getDatasourceType() {
        return DatasourceType.MYSQL.getName();
    }

    @Override
    public String getOperateType() {
        return OperateType.INSERT.getName();
    }

    @Override
    public Object execute(ApiInfoDetailDto apiInfoDetailDto) {
        Integer result = 0;
        ApiDatasourceDto datasourceDto = apiInfoDetailDto.getDatasourceDto();
        if (null == datasourceDto) {
            throw new ApplicationException(ResultCode.FAIL_CODE, "数据源获取异常");
        }
        Connection connect = dataSourceHelp.getConnect(datasourceDto);
        Statement statement = null;
        String insertSql = sqlHandler.generateInsertSql(apiInfoDetailDto);
        try {
            statement = connect.createStatement();
            statement.execute("use " + apiInfoDetailDto.getDatabaseName());
            statement.execute(insertSql);
            result = statement.getUpdateCount();
        } catch (Exception e) {
            log.error("mysql insert异常 errMsg:{}", e.getMessage());
        } finally {
            try {
                if (null != statement) {
                    statement.close();
                }
                if (null != connect) {
                    connect.close();
                }
            } catch (Exception e) {
                log.error("关流异常 errMsg:{}", e.getMessage());
            }
        }
        log.info("mysql insert {} 条数据", result);
        return result;
    }

}
